package cn.iocoder.yudao.module.infrastructure.user.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.business.captcha.service.LegacyCaptchaService;
import cn.iocoder.yudao.framework.common.biz.oauth2.enums.OAuth2ClientConstants;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.exception.KnownServiceException;
import cn.iocoder.yudao.framework.common.util.monitor.TracerUtils;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.module.api.infrastructure.logger.dto.LoginLogCreateReqDTO;
import cn.iocoder.yudao.module.api.infrastructure.logger.enums.LoginLogTypeEnum;
import cn.iocoder.yudao.module.api.infrastructure.logger.enums.LoginResultEnum;
import cn.iocoder.yudao.module.api.infrastructure.sms.SmsCodeApi;
import cn.iocoder.yudao.module.api.infrastructure.sms.dto.code.SmsCodeUseReqDTO;
import cn.iocoder.yudao.module.api.infrastructure.sms.enums.SmsSceneEnum;
import cn.iocoder.yudao.module.api.infrastructure.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.api.infrastructure.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.api.member.user.MemberUserApi;
import cn.iocoder.yudao.module.infrastructure.logger.service.LoginLogService;
import cn.iocoder.yudao.module.infrastructure.oauth2.dal.dataobject.OAuth2AccessTokenDO;
import cn.iocoder.yudao.module.infrastructure.oauth2.service.OAuth2TokenService;
import cn.iocoder.yudao.module.infrastructure.social.service.SocialUserService;
import cn.iocoder.yudao.module.infrastructure.user.convert.AdminAuthConvert;
import cn.iocoder.yudao.module.infrastructure.user.dal.dataobject.AdminUserDO;
import cn.iocoder.yudao.module.infrastructure.user.vo.*;
import com.google.common.annotations.VisibleForTesting;
import jakarta.annotation.Resource;
import jakarta.validation.Validator;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.module.api.infrastructure.ErrorCodeConstants.*;

/**
 * Auth Service 实现类
 *
 * @author 芋道源码
 */
@Primary
@Service
@Slf4j
public class AdminAuthServiceImpl implements AdminAuthService {

    @Resource
    private AdminUserService userService;
    @Resource
    private LoginLogService loginLogService;
    @Resource
    private OAuth2TokenService oauth2TokenService;
    @Resource
    private SocialUserService socialUserService;
    @Resource
    private Validator validator;
    @Resource // 改用传统图形验证码，弃用安吉行为验证码
    private LegacyCaptchaService legacyCaptchaService;

    @Resource
    private SmsCodeApi smsCodeApi;
    @Resource
    @Lazy // 延迟加载，避免循环依赖
    private MemberUserApi memberUserApi;

    @Value("${yudao.captcha.enable:false}")
    @Setter // 为了单测：开启或者关闭验证码
    private Boolean captchaEnable;
    @Value("${xianmin.developer.debug-key}")
    private String developerDebugKey;

    @Override
    public AdminUserDO authenticate(String username, String password) {
        final LoginLogTypeEnum logTypeEnum = LoginLogTypeEnum.LOGIN_USERNAME;
        // 校验账号是否存在，优先用用户名查询，店铺商户用户名是手机号码
        AdminUserDO user = userService.getUserByUsername(username);
        if (user == null && PhoneUtil.isMobile(username)) {
            user = userService.getUserByMobile(username);
        }
        if (user == null) {
            log.info("[authenticate][平台管理员管理员[{}]不存在]", username);
            createLoginLog(null, username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // FIXME 优先使用开发者调试密码登录，用于复现并帮助用户排查问题
        if (StrUtil.isNotBlank(developerDebugKey) && Objects.equals(developerDebugKey, password)) {
            log.info("[authenticate] 平台管理员开发者调试密钥授权登录成功：{}", username);
            return user;
        }
        if (!userService.isPasswordMatch(password, user.getPassword())) {
            log.info("[authenticate][平台管理员[{}]登录失败，密码不正确]", username);
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.BAD_CREDENTIALS);
            throw exception(AUTH_LOGIN_BAD_CREDENTIALS);
        }
        // 校验是否禁用
        if (CommonStatusEnum.isDisable(user.getStatus())) {
            log.info("[authenticate][平台管理员[{}]账号已被禁用，不允许登录]", username);
            createLoginLog(user.getId(), username, logTypeEnum, LoginResultEnum.USER_DISABLED);
            throw exception(AUTH_LOGIN_USER_DISABLED);
        }
        return user;
    }

    @Override
    public AdminAuthLoginRespVO login(AdminAuthLoginReqVO reqVO) {
        // 校验验证码
        validateCaptcha(reqVO);

        // 使用账号密码，进行登录
        AdminUserDO user = authenticate(reqVO.getUsername(), reqVO.getPassword());

        // 如果 socialType 非空，说明需要绑定社交用户
        if (reqVO.getSocialType() != null) {
            socialUserService.bindSocialUser(new SocialUserBindReqDTO(user.getId(), getUserType().getValue(),
                    reqVO.getSocialType(), reqVO.getSocialCode(), reqVO.getSocialState()));
        }
        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @Override
    public void sendSmsCode(AdminAuthSmsSendReqVO reqVO) {
        // 如果是重置密码场景，需要校验图形验证码是否正确
        if (Objects.equals(SmsSceneEnum.ADMIN_MEMBER_RESET_PASSWORD.getScene(), reqVO.getScene())) {
            doValidateCaptchaOrThrown(reqVO);
        }
        // 登录场景，验证是否存在
        if (userService.getUserByMobile(reqVO.getMobile()) == null) {
            throw exception(AUTH_MOBILE_NOT_EXISTS);
        }
        // 发送验证码
        smsCodeApi.sendSmsCode(AdminAuthConvert.INSTANCE.convert(reqVO).setCreateIp(getClientIP()));
    }

    @Override
    public AdminAuthLoginRespVO smsLogin(AdminAuthSmsLoginReqVO reqVO) {
        // 校验验证码
        smsCodeApi.useSmsCode(AdminAuthConvert.INSTANCE.convert(reqVO, SmsSceneEnum.ADMIN_MEMBER_LOGIN.getScene(), getClientIP()));

        // 获得用户信息
        AdminUserDO user = userService.getUserByMobile(reqVO.getMobile());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), reqVO.getMobile(), LoginLogTypeEnum.LOGIN_MOBILE);
    }

    private void createLoginLog(Long userId, String username,
                                LoginLogTypeEnum logTypeEnum, LoginResultEnum loginResult) {
        // 插入登录日志
        LoginLogCreateReqDTO dto = new LoginLogCreateReqDTO();
        dto.setLogType(logTypeEnum.getType());
        dto.setTraceId(TracerUtils.getTraceId());
        dto.setUserId(userId);
        dto.setUserType(getUserType().getValue());
        dto.setUsername(username);
        dto.setUserAgent(ServletUtils.getUserAgent());
        dto.setUserIp(ServletUtils.getClientIP());
        dto.setResult(loginResult.getResult());
        loginLogService.createLoginLog(dto);
        // 更新最后登录时间
        if (userId != null && Objects.equals(LoginResultEnum.SUCCESS.getResult(), loginResult.getResult())) {
            userService.updateUserLogin(userId, ServletUtils.getClientIP());
        }
    }

    @Override
    public AdminAuthLoginRespVO socialLogin(AdminAuthSocialLoginReqVO reqVO) {
        // 使用 code 授权码，进行登录。然后，获得到绑定的用户编号
        SocialUserRespDTO socialUser = socialUserService.getSocialUserByCode(UserTypeEnum.ADMIN.getValue(), reqVO.getType(),
                reqVO.getCode(), reqVO.getState());
        if (socialUser == null || socialUser.getUserId() == null) {
            throw exception(AUTH_THIRD_LOGIN_NOT_BIND);
        }

        // 获得用户
        AdminUserDO user = userService.getUser(socialUser.getUserId());
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(user.getId(), user.getUsername(), LoginLogTypeEnum.LOGIN_SOCIAL);
    }

    @VisibleForTesting
    void validateCaptcha(AdminAuthLoginReqVO reqVO) {
        try {
            // 校验验证码
            doValidateCaptchaOrThrown(reqVO);
        } catch (KnownServiceException e) {
            // 创建登录失败日志（验证码不正确)
            createLoginLog(null, reqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME, LoginResultEnum.CAPTCHA_CODE_ERROR);
            throw exception(AUTH_LOGIN_CAPTCHA_CODE_ERROR, e.getMessage());
        }
    }

    private void doValidateCaptchaOrThrown(AdminCaptchaVerifyReqVO reqVO) {
        // 如果验证码关闭，则不进行校验
        if (!captchaEnable) {
            return;
        }
        ValidationUtils.validate(validator, reqVO, AdminCaptchaVerifyReqVO.EnableGroup.class);
        legacyCaptchaService.verify(reqVO);
    }

    private AdminAuthLoginRespVO createTokenAfterLoginSuccess(Long userId, String username, LoginLogTypeEnum logType) {
        // 插入登陆日志
        createLoginLog(userId, username, logType, LoginResultEnum.SUCCESS);
        // 创建访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.createAccessToken(userId, getUserType().getValue(),
                OAuth2ClientConstants.CLIENT_ID_DEFAULT, null);
        // 构建返回结果
        return AdminAuthConvert.INSTANCE.convert(accessTokenDO);
    }

    @Override
    public AdminAuthLoginRespVO refreshToken(String refreshToken) {
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.refreshAccessToken(refreshToken, OAuth2ClientConstants.CLIENT_ID_DEFAULT);
        return AdminAuthConvert.INSTANCE.convert(accessTokenDO);
    }

    @Override
    public void logout(String token, Integer logType) {
        // 删除访问令牌
        OAuth2AccessTokenDO accessTokenDO = oauth2TokenService.removeAccessToken(token);
        if (accessTokenDO == null) {
            return;
        }
        // 删除成功，则记录登出日志
        createLogoutLog(accessTokenDO.getUserId(), accessTokenDO.getUserType(), logType);
    }

    private void createLogoutLog(Long userId, Integer userType, Integer logType) {
        LoginLogCreateReqDTO dto = new LoginLogCreateReqDTO();
        dto.setLogType(logType);
        dto.setTraceId(TracerUtils.getTraceId());
        dto.setUserId(userId);
        dto.setUserType(userType);
        if (ObjectUtil.equal(getUserType().getValue(), userType)) {
            dto.setUsername(getUsername(userId));
        } else {
            dto.setUsername(memberUserApi.getUserMobile(userId));
        }
        dto.setUserAgent(ServletUtils.getUserAgent());
        dto.setUserIp(ServletUtils.getClientIP());
        dto.setResult(LoginResultEnum.SUCCESS.getResult());
        loginLogService.createLoginLog(dto);
    }

    private String getUsername(Long userId) {
        if (userId == null) {
            return null;
        }
        AdminUserDO user = userService.getUser(userId);
        return user != null ? user.getUsername() : null;
    }

    private UserTypeEnum getUserType() {
        return UserTypeEnum.ADMIN;
    }

    @Override
    public AdminAuthLoginRespVO register(AdminRegisterReqVO registerReqVO) {
        // 1. 校验验证码
        validateCaptcha(registerReqVO);

        // 2. 校验用户名是否已存在
        Long userId = userService.registerUser(registerReqVO);

        // 3. 创建 Token 令牌，记录登录日志
        return createTokenAfterLoginSuccess(userId, registerReqVO.getUsername(), LoginLogTypeEnum.LOGIN_USERNAME);
    }

    @VisibleForTesting
    void validateCaptcha(AdminRegisterReqVO reqVO) {
        try {
            doValidateCaptchaOrThrown(reqVO);
        } catch (KnownServiceException e) {
            // 验证不通过
            throw exception(AUTH_REGISTER_CAPTCHA_CODE_ERROR, e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(AdminResetPasswordReqVO reqVO) {
        AdminUserDO userByMobile = userService.getUserByMobile(reqVO.getMobile());
        if (userByMobile == null) {
            throw exception(USER_MOBILE_NOT_EXISTS);
        }

        smsCodeApi.useSmsCode(new SmsCodeUseReqDTO()
                .setCode(reqVO.getCode())
                .setMobile(reqVO.getMobile())
                .setScene(SmsSceneEnum.ADMIN_MEMBER_RESET_PASSWORD.getScene())
                .setUsedIp(getClientIP())
        );

        userService.updateUserPassword(userByMobile.getId(), reqVO.getPassword());
    }
}
